<template>
  <section class="voucher-detail">
    <info
      :clientInfo="clientInfo"
      :tagText="clientInfo.forceBills ? '无核对' : ''"
    >
      <template v-slot:after>
        <div class="info-tip">最新结账日期：{{ month }}月</div>
      </template>
    </info>
    <div class="common-text-block-section">
      <div class="btns">
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click.native="select"
          size="small"
          >过滤条件</el-button
        >
        <el-link :href="downloadCertificateUri"  :disabled="!datePickerValue.length"
                :underline="false" target="_blank"
                >
                <el-button
                  :disabled="!datePickerValue.length"
                  icon="el-icon-download"
                  type="primary"
                  size="small"
                >导出总账表格</el-button>
              </el-link>
        <el-popover
            ref="accountSubmitPopOver"
            placement="bottom"
            :visible-arrow="false"
            popper-class="accountSubmitPopOver"
            trigger="click"
        >
            <div  class="backgroundContent" style="max-height:800px;">
            <section class="inner-text-block-section">
            <div class="title-section" style="margin-left:20;">
            <div class="title">凭证预览</div>
            </div>
            <div class="form-section" id="certificate">
            <!-- <div class="everypage" style="width:100%; margin-top:20px; min-height: 1028px;" v-for="(entry, key, i) in printableEntryList" :key="i"> -->
            <div class="everypage" style="width:100%; margin-top:20px;" v-for="(entry, key, i) in printableEntryList" :key="i">
            <center style="font-size: 20px;font-weight: 600;">记账凭证</center>
            <center style="font-size:16px; font-weight:600;text-decoration:underline;">{{clientInfo.companyName}}</center>
            <div><div style="float:left">记账时间： {{new Date().getFullYear()}}年{{new Date().getMonth() + 1}}月{{new Date().getDate()}}日</div> <div style="float:right;">分录编号: {{key}}</div></div>
            <el-table
            align="center"
            :data="printableEntryList[key]"
            :span-method="printableArraySpanMethod"
            border
            style="width: 100%">
            <el-table-column
                align="center"
                label="会计科目">
                <template slot-scope="scope">
                {{ scope.row.borrowSubject ? scope.row.borrowSubject:scope.row.loanSubject }}
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                label="对手方">
                <template slot-scope="scope">
                {{ scope.row.borrowSide ? scope.row.borrowSide:scope.row.loanSide }}
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                label="借方金额">
                <template slot-scope="scope">
                {{ scope.row.borrowAmount ? scope.row.borrowAmount : "" }}
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                label="贷方金额">
                <template slot-scope="scope">
                {{ scope.row.loanAmount ?scope.row.loanAmount : "" }}
                </template>
            </el-table-column>
            </el-table>
            </div>
            </div>
            <div style="
            display: flex;
                justify-content: space-between;
                align-items: center;
            margin:5px;">
            <el-button size="small" style="margin:0 auto;" type="primary" @click="handleWindowPrint('#certificate', clientInfo.companyName)">打印PDF</el-button>
            </div>
            </section>
            </div>
            <el-button slot="reference" icon="el-icon-document" 
            :disabled="!datePickerValue.length"
            type="primary" size="small" >打印凭证
            </el-button>
        </el-popover>
        <el-link :href="exportExcelUri" :disabled="!datePickerValue.length"
                :underline="false" target="_blank">
                <el-button
                  :disabled="!datePickerValue.length"
                  icon="el-icon-download"
                  type="primary"
                  size="small"
                >导出报表</el-button>        
        </el-link>
        
      </div>
      <div class="data-table-content">
        <el-tabs tab-position="left" lazy>
          <el-tab-pane label="会计分录" name="0" lazy>
            <entryTable :data="entryList"></entryTable>
          </el-tab-pane>
          <el-tab-pane label="总账" name="1" lazy>
            <totalTable :data="totalList" />
          </el-tab-pane>
          <el-tab-pane label="明细表" name="2" lazy>
            <detailTable :data="detailList" />
          </el-tab-pane>
          <el-tab-pane label="债权债务情况" name="3" lazy>
            <debtDetailTable :data="debtList" />
          </el-tab-pane>
          <el-tab-pane label="利润表" name="4" lazy>
            <profitTable :data="profitList" />
          </el-tab-pane>
          <el-tab-pane label="资产负债表" name="5" lazy>
            <assetsLiabilities :data="balanceList" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <el-dialog
      destroy-on-close
      title="过滤条件"
      :visible.sync="isShow"
      width="40%"
      @close="clear"
    >
      <div class="dialog-content">
        <div class="filter-stage">
          <div class="filter-title">选择会计周期</div>
          <div>
            <el-date-picker
             v-model="datePickerValue"
             type="monthrange"
             range-separator="至"
             start-placeholder="开始月份"
             value-format="yyyy-MM"
             end-placeholder="结束月份">
             
            </el-date-picker>
          </div>
          <div class="filter-title filter-module">选择科目范围</div>
          <subjectSelect v-model="startSubjectCode" />
          到
          <subjectSelect v-model="endSubjectCode" />
        </div>
        <div class="dialog-tip">
          提示：若不选择时间和科目范围，则默认导出全部科目，所有时间内的对应的账薄。
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onConfirm" :loading="isCreateing">确定生成</el-button>
        </div>
      </div>
    </el-dialog>
  </section>
</template>


<script>
import info from "../../components/infoHeader";
import map from "@/components/map";
import subjectSelect from "@/components/subjectSelect";
import utils, { getUrlParams, getPreMonth } from "@/components/utiles";

import entryTable from "./entryTable";
import detailTable from "./detailTable";
import totalTable from "./totalTable";
import debtDetailTable from './debtDetailTable';
import profitTable from "@/pages/smartBill/components/profitTable";
import assetsLiabilities from "@/pages/smartBill/components/assetsLiabilities.vue";

import {
  createRowData,
  balanceDataToTable,
  entryListToTable,
} from "./dataHelper";


let tmpSelect = {};

export default {
  data() {
    return {
      clientInfo: {},
      isShow: false,
      startSubjectCode: null,
      endSubjectCode: null,
      month: null,
      totalList: [],
      detailList: [],
      entryList: [],
      profitList: [], // 利润表
      balanceList: [], // 资产负债表
      currentUser: {},
      datePickerValue: [],
      isCreateing: false,
      debtList: [],
      entryList: null,
      printableEntryList: {}
    };
  },
  components: {
    info,
    subjectSelect,
    entryTable,
    detailTable,
    totalTable,
    debtDetailTable,
    profitTable,
    assetsLiabilities
  },
  computed: {
    downloadCertificateUri() {
      const currentUser = utils.getCurrentUser();
      return getUrlParams("/api/book/downloadExcel", {
        bName: currentUser.bCompanyName,
        cName: this.clientInfo.companyName,
        startMonth: this.datePickerValue[0],
        endMonth: this.datePickerValue[1],
        startSubjectCode: this.startSubjectCode,
        endSubjectCode: this.endSubjectCode,
      });
    },
    // 导出报表
    exportExcelUri(){
        const currentUser = utils.getCurrentUser();
        return getUrlParams("/api/book/downloadSheetExcel", {
            bName: currentUser.bCompanyName,
            cName: this.clientInfo.companyName,
            startMonth: this.datePickerValue[0],
            endMonth: this.datePickerValue[1]
        });
    }
  },
  created() {
    const data = localStorage.getItem("historyDetail");
    if (data) {
      this.clientInfo = JSON.parse(data);
      this.month =
        this.clientInfo.status === 10
          ? new Date().getMonth() + 1
          : getPreMonth();
    }
  },
  methods: {
    select() {
      const {
        startSubjectCode,
        endSubjectCode,
        datePickerValue
      } = this;
      tmpSelect = {
        startSubjectCode,
        endSubjectCode,
        datePickerValue
      };
      this.isShow = true;
    },
    clear() {
      Object.assign(this, tmpSelect);
    },
    async onConfirm() {
      tmpSelect = {};
      await this.loadData();
      this.isShow = false;
    },
    upload() {},
    loadData() {
        console.log("####start loading data")
        this.currentUser = utils.getCurrentUser()
      const {
        startSubjectCode,
        endSubjectCode,
        clientInfo,
        datePickerValue
      } = this;
      this.isCreateing = true;
      // 获取利润表和资产负债表
      let params = {
          startMonth: datePickerValue[0],
          endMonth: datePickerValue[1],
          bName: this.currentUser.bCompanyName, 
          cName: clientInfo.companyName,
      }
      
      console.log("获取利润表和资产负债表, params: ", params)
      this.$http.post("/book/generateAccountBookSheet", params).then((res)=>{
          console.log("####data", res.data, res.code)
          let {balanceSheet, incomeSheet} = res.data;
            this.profitList = incomeSheet.itemList || [],
            this.balanceList = balanceDataToTable(balanceSheet);
      })
      this.$http.post("/book/generateAccountBook", {
          startMonth: datePickerValue[0],
          endMonth: datePickerValue[1],
          startSubjectCode,
          endSubjectCode,
          companyName: clientInfo.companyName,
        })
        .then((res) => {
          let { accountingEntry, totalAccountBook, detailAccountBook, specialDetailList } =
            res.data;
          let newData = {};

          accountingEntry = accountingEntry || {
            entryList: [],
          };
          totalAccountBook = totalAccountBook || {
            itemList: [],
          };

          detailAccountBook = detailAccountBook || {
            ledgerDetail: [],
          };

          specialDetailList = specialDetailList || {
            ledgerDetail: [],
          };

          // 处理分录表数据
          newData.entryList = entryListToTable(accountingEntry.entryList);
          this.entryList = newData.entryList
          this.formatEntryList()

          let totalList = [
            {
              // 需要合并的列index, 不需要合并的也要写
              columnIndexs: [0, 1, 4, 6],
              // 对应需要合并的列需要合并几个，1表示显示不合并，
              colSpans: [1, 2, 2, 2],
              // 标题列
              headerTypes: [2, 4, 6],
              rowMerge: true,
              rowColumnIndexs: [0],
              rowSpans: [2],
              ...createRowData([
                "科目",
                "期初值",
                "",
                "发生额",
                "",
                "期末值",
                "",
              ]),
            },
            {
              headerTypes: [1, 2, 3, 4, 5, 6],
              // 需要合并的行
              rowMerge: true,
              // 需要合并的行的列
              rowColumnIndexs: [0],
              // 合并的行需要合并几行
              rowSpans: [0,],
              ...createRowData([
                "",
                "",
                "借方",
                "贷方",
                "借方",
                "贷方",
                "借方",
                "贷方",
              ]),
            },
          ];

          if (totalAccountBook.itemList) {
            totalList = totalList.concat(
              totalAccountBook.itemList.map((v) =>
                createRowData([
                  v.subject,
                  v.tradeSide,
                  v.periodStartValue && v.periodStartValue.borrowAmount,
                  v.periodStartValue && v.periodStartValue.loanAmount,
                  v.periodCurrentValue && v.periodCurrentValue.borrowAmount,
                  v.periodCurrentValue && v.periodCurrentValue.loanAmount,
                  v.periodEndValue && v.periodEndValue.borrowAmount,
                  v.periodEndValue && v.periodEndValue.loanAmount,
                ])
              )
            );
          }

          newData.totalList = totalList;

         
          this.getDetailList(newData, detailAccountBook.ledgerDetail, 'detailList');

          this.getBtDetailList(newData, specialDetailList, 'debtList');
          console.log(newData.debtList);

          Object.assign(this, newData);
        }).finally(() => {
          this.isCreateing = false
        });
    },
    getTypeValue(obj) {
      let result = ["", ""];
      if (obj) {
        result[obj.type] = obj.amount;
      }
      return result;
    },
    getDetailList(newData, initData, name) {
      let detailList = [
            {
              columnIndexs: [0, 4],
              // 对应需要合并的列需要合并几个，1表示显示不合并，
              colSpans: [4, 4],
              // 标题列
              headerTypes: [0, 4],
              ...createRowData([
                "科目编号",
                "",
                "",
                "",
                "科目名称",
                "",
                "",
                "",
                1,
              ]),
            },
          ];
       // 明细表
          (initData || []).forEach(
            (v, i) => {
              let list = [
                {
                  columnIndexs: [0, 4],
                  // 对应需要合并的列需要合并几个，1表示显示不合并，
                  colSpans: [4, 4],
                  // 标题列
                  headerTypes: [0, 4],
                  ...createRowData([
                    v.subjectCode,
                    "",
                    "",
                    "",
                    v.subjectName,
                    "",
                    "",
                    "",
                    "a" + i,
                  ]),
                },
                {
                  columnIndexs: [0],
                  colSpans: [8],
                  hasChildren: true,
                  children: [],
                  ...createRowData([
                    "点击展开",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "e" + i,
                  ]),
                },
              ];
              // if(v.itemList) {

              const [startBrrow, startLoan] = this.getTypeValue(v.startValue);
              const [endBrrowItem, endLoanItem] = (v.endValue || []).map((v2) =>
                this.getTypeValue(v2)
              );
              const [balanceEndBrrow, balanceEndLoan] = this.getTypeValue(
                v.balanceEndValue
              );
              list[1].children = [
                {
                  columnIndexs: [0, 1, 2, 3, 4, 6],
                  // 对应需要合并的列需要合并几个，1表示显示不合并，
                  colSpans: [1, 1, 1, 1, 2, 2],
                  rowMerge: true,
                  rowColumnIndexs: [0, 1, 2, 3],
                  rowSpans: [2, 2, 2, 2],
                  // 标题列
                  headerTypes: [4, 6],
                  ...createRowData([
                    "项目",
                    "时间",
                    "对手方科目",
                    "备注",
                    "本期发生额",
                    "",
                    "余额",
                    "",
                    "b" + i,
                  ]),
                },
                {
                  // 需要合并的行
                  rowMerge: true,
                  // 需要合并的行的列
                  rowColumnIndexs: [0, 1, 2, 3],
                  // 合并的行需要合并几行
                  rowSpans: [0, 0, 0, 0],
                  ...createRowData([
                    "",
                    "",
                    "",
                    "",
                    "借方",
                    "贷方",
                    "借方",
                    "贷方",
                    "c" + i,
                  ]),
                },
                {
                  ...createRowData([
                    "期初值",
                    "",
                    "",
                    "",
                    "",
                    "",
                    startBrrow,
                    startLoan,
                    "d" + i,
                  ]),
                },
              ];
              if (v.itemList && v.itemList.length) {
                list[1].children.push(
                  ...(v.itemList || []).map((v2, i2) => {
                    const [item0, item1] = this.getTypeValue(v2.balance)
                    const [item3, item4] = this.getTypeValue(v2.currentValue) 

                    return {
                      rowMerge: true,
                      rowColumnIndexs: [0],
                      rowSpans: i2 ? [0] : [v.itemList.length],
                      ...createRowData([
                        "发生额",
                        v2.date,
                        v2.tradeSideSubject,
                        v2.remark,
                        item3, 
                        item4,
                        item0,
                        item1,
                        "h" + i + "_" + i2,
                      ]),
                    };
                  })
                );
              }

              list[1].children.push({
                ...createRowData([
                  "期末值",
                  "",
                  "",
                  "",
                  endBrrowItem && endLoanItem
                    ? endBrrowItem[0] || endLoanItem[0]
                    : "",
                  endBrrowItem && endLoanItem
                    ? endBrrowItem[1] || endLoanItem[1]
                    : "",
                  balanceEndBrrow,
                  balanceEndLoan,
                  "f" + i,
                ]),
              });
              // }
              detailList.push(...list);
            }
          );
          newData[name] = detailList;
    },
    getBtDetailList(newData, initData, name) {
       const { type, amount } = initData.totalAmount || {};
      let detailList = [
            {
              columnIndexs: [0, 3, 6],
              // 对应需要合并的列需要合并几个，1表示显示不合并，
              colSpans: [3, 3, 3],
              // 标题列
              headerTypes: [0, 3, 6],
              ...createRowData([
                "科目",
                "",
                "",
                "借方余额",
                "",
                "",
                "贷方余额",
                "",
                "",
                'mm1',
              ]),
            },
            {
                  columnIndexs: [0, 3, 6],
                  // 对应需要合并的列需要合并几个，1表示显示不合并，
                  colSpans: [3, 3, 3],
                  // 标题列
                  headerTypes: [0, 3, 6],
                  ...createRowData([
                    '合计',
                    "",
                    "",
                    type === 0 ? amount : '',
                    "",
                    "",
                     type === 1 ? amount : '',
                    "",
                    "",
                    "nn2",
                  ]),
                },
                {
                  columnIndexs: [0],
                  colSpans: [9],
                  col9Title: 'gg2'
                }
          ];
       // 明细表
          (initData.ledgerDetail || []).forEach(
            (v, i) => {
              let list = [
                {
                  columnIndexs: [0, 3],
                  // 对应需要合并的列需要合并几个，1表示显示不合并，
                  colSpans: [3, 6],
                  // 标题列
                  headerTypes: [0, 3],
                  ...createRowData([
                    '对手方',
                    "",
                    "",
                    v.rivalName,
                    "",
                    "",
                    '',
                    "",
                    "",
                    "ww" + i,
                  ]),
                },
                {
                  columnIndexs: [0],
                  colSpans: [9],
                  hasChildren: true,
                  children: [],
                  ...createRowData([
                    "点击展开",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "kk" + i,
                  ]),
                },
              ];
              // if(v.itemList) {

              const [startBrrow, startLoan] = this.getTypeValue(v.startValue);
              const [endBrrowItem, endLoanItem] = (v.endValue || []).map((v2) =>
                this.getTypeValue(v2)
              );
              const [balanceEndBrrow, balanceEndLoan] = this.getTypeValue(
                v.balanceEndValue
              );
              list[1].children = [
                {
                  columnIndexs: [0, 1, 2, 3, 4, 5, 7],
                  // 对应需要合并的列需要合并几个，1表示显示不合并，
                  colSpans: [1, 1, 1, 1, 1, 2, 2],
                  rowMerge: true,
                  rowColumnIndexs: [0, 1, 2, 3, 4],
                  rowSpans: [2, 2, 2, 2, 2],
                  // 标题列
                  headerTypes: [4, 6],
                  ...createRowData([
                    "项目",
                    "时间",
                    "债务科目",
                    "对手方科目",
                    "备注",
                    "本期发生额",
                    "",
                    "余额",
                    "",
                    "bb" + i,
                  ]),
                },
                {
                  // 需要合并的行
                  rowMerge: true,
                  // 需要合并的行的列
                  rowColumnIndexs: [0, 1, 2, 3],
                  // 合并的行需要合并几行
                  rowSpans: [0, 0, 0, 0],
                  ...createRowData([
                    "",
                    "",
                    "",
                    "",
                    "借方",
                    "贷方",
                    "借方",
                    "贷方",
                    "",
                    "cc" + i,
                  ]),
                },
                {
                  ...createRowData([
                    "期初值",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    startBrrow,
                    startLoan,
                    "dd" + i,
                  ]),
                },
              ];
              if (v.itemList && v.itemList.length) {
                list[1].children.push(
                  ...(v.itemList || []).map((v2, i2) => {
                    const [item0, item1] = this.getTypeValue(v2.balance)
                    const [item3, item4] = this.getTypeValue(v2.currentValue) 

                    return {
                      rowMerge: true,
                      rowColumnIndexs: [0],
                      rowSpans: i2 ? [0] : [v.itemList.length],
                      ...createRowData([
                        "发生额",
                        v2.date,
                        v2.debtSubject,
                        v2.tradeSideSubject,
                        v2.remark,
                        item3, 
                        item4,
                        item0,
                        item1,
                        "hh" + i + "_" + i2,
                      ]),
                    };
                  })
                );
              }

              list[1].children.push({
                ...createRowData([
                  "期末值",
                  "",
                  "",
                  "",
                  "",
                  endBrrowItem && endLoanItem
                    ? endBrrowItem[0] || endLoanItem[0]
                    : "",
                  endBrrowItem && endLoanItem
                    ? endBrrowItem[1] || endLoanItem[1]
                    : "",
                  balanceEndBrrow,
                  balanceEndLoan,
                  "ff" + i,
                ]),
              });
              // }
              detailList.push(...list);
            }
          );
          newData[name] = detailList;
    },
    formatEntryList(){
        console.log("####账簿查询分录数据", this.entryList)
        let maps = {}; // 同一单号对手方数量的存储数据结构
        this.entryList.forEach((item, index, array) => {
        if (maps[item.no] != undefined){
            maps[item.no]+=1;
        } else {
            maps[item.no] = 0;
        }
        if (this.printableEntryList[item.no]) {
            this.printableEntryList[item.no][maps[item.no]] = item;
        } else {
            this.printableEntryList[item.no] = [item]
        }
        })
        Object.keys(this.printableEntryList).forEach((item, index, array) => {
            this.printableEntryList[item][maps[item] + 1] = {loanSubject: "备注", borrowSide: this.printableEntryList[item][0].desc};
        });
        console.log("####格式化分录数据end", this.printableEntryList)
    },
    printableArraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (row.loanSubject == "备注") {
          if (columnIndex === 1) {
            return [1, 3];
          } else if (columnIndex === 1) {
            return [0, 0];
          }
        }
      },
    async handleWindowPrint(ele, companyName){
        console.log("666", document.head.innerHTML);
        let date = new Date();
        let month = date.getMonth() + 1;
        document.body.innerHTML =  document.querySelector( ele ).outerHTML;
        document.head.innerHTML = await document.head.innerHTML.replace(/<title>.*<\/title>/, ' <title>' + companyName + '_' + month + '</title>\n' +
        '<!--abcdefghijklmnopqrstuvwxyz-->'
        )
        while (document.head.innerHTML.indexOf('abcdefghijklmnopqrstuvwxyz') == -1 ){
          await sleep(10);
        }
        window.print();
        window.location.reload();
    }
  },
};
</script>
<style  lang="less" scoped>
@import "../../assets/var.less";

.voucher-detail {
  padding: 0 10px;
}
.header-item {
  font-size: 14px;
  color: #333;
}
.info-tip {
  margin-top: 10px;
}
.filter-title {
  margin: 20px 0 10px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
.dialog-tip {
  margin-top: 20px;
}

.data-table-content {
  margin-top: 30px;
}

.inner-text-block-section {
    .title-section,
    .inner-title-section {
        border-bottom: 1px solid #aaa;
        margin: 0 0 0 0;
        font-size: 16px;
        .title {
            border-left: 4px solid #1890ff;
            padding-left: 10px;
            margin: 10px 0;
        }
        .el-button--text {
            float: right;
            padding: 0;
        }
        .iconfont {
            margin-left: 7px;
        }
        .icon-edit {
            font-size: 12px;
        }
        .right {
            float: right;
            padding-right: 10px;
            font-size: 14px;
            color: @color-grey-low;
        }
    }
    .inner-title-section {
        margin: 0 0 20px 0;
    }

    .disc-section{
      font-size: 16;
      padding:10px;
      border-bottom: 1px solid #aaa;
    }

    .form-section{
      width:auto;
      max-height: 500px;
      margin-top: 10px;
      border-bottom: 1px solid #aaa;
      overflow: auto;
    }
    
    .text-section {
        > .item {
            display: inline-block;
            width: 206px;
            line-height: 2em;
        }
        > .single-line {
            display: block;
            width: auto;
        }
    }
}
</style>
<style lang="less">
  .accountSubmitPopOver{
    margin:0;
    padding:0;
    border: 1px solid #888;
    max-height: 100%;
    border-radius: 0;
    width:734px;
}
</style>